package com.zmm.weblog.jwt.service;

import com.zmm.weblog.common.domain.dos.UserDo;
import com.zmm.weblog.common.domain.dos.UserRoleDo;
import com.zmm.weblog.common.domain.mapper.UserMapper;
import com.zmm.weblog.common.domain.mapper.UserRoleMapper;
import io.jsonwebtoken.lang.Collections;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author:福禄寿
 * @Date:2024/4/27 下午10:23
 * @Des:weblog-springboot
 **/
@Slf4j
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;



    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从数据库中查询
        UserDo user = userMapper.findByUsername(username);
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("用户不存在");
        }

        String[] roleArr = null;
        //查询用户角色
        List<UserRoleDo> roleDos = userRoleMapper.selectByUsername(username);
        // 转数组
        if (!CollectionUtils.isEmpty(roleDos)) {
            List<String> roles = roleDos.stream().map(p -> p.getRole()).collect(Collectors.toList());
            roleArr = roles.toArray(new String[roles.size()]);
        }

        return User.withUsername(user.getUsername())
                .password(user.getPassword())
                .authorities(roleArr)
                .build();
    }

}
